package top.huntwolf.admin.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.huntwolf.admin.common.enums.CodeMsg;
import top.huntwolf.admin.dao.BookStorageDao;
import top.huntwolf.admin.exception.ServiceException;
import top.huntwolf.admin.pojo.book.BuyBook;
import top.huntwolf.admin.pojo.storage.BookStorage;
import top.huntwolf.admin.pojo.storage.TransferVo;
import top.huntwolf.admin.utils.RedisUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BookStorageService {


    @Autowired
    private BookStorageDao storageDao;

    @Autowired
    private RedisUtil redisUtil;

    public Integer addBookStorage(List<BookStorage> storages){
        int sum = 0;
        List<BookStorage> newStorages = new ArrayList<>();
        Date date = new Date();
        for (BookStorage bookStorage : storages){
            bookStorage.setUpdateTime(date);
            bookStorage.setCreateTime(date);
            sum += bookStorage.getStorage();
            BookStorage storage = storageDao.selectRepeatStorage(bookStorage);
            if (storage!=null){
                storage.setStorage(bookStorage.getStorage());
                storage.setUpdateTime(date);
                storageDao.increaseStorage(storage);
            }else {
                newStorages.add(bookStorage);
            }
        }
        if (newStorages.size()>0){
            storageDao.insert(newStorages);
        }
        //存储总库存数量
        redisUtil.incr("Total inventory",sum);
        return sum;
    }

    public void modifyStorage(BookStorage bookStorage){
        bookStorage.setUpdateTime(new Date());
        storageDao.update(bookStorage);
    }

    public void transferBook(TransferVo transfer){
        BookStorage origin = storageDao.select(transfer.getOrigin());
        BookStorage target = storageDao.select(transfer.getTarget());
        if(origin == null||target == null){
            throw new ServiceException(CodeMsg.STORAGE_ID_NON_EXIST);
        }
        if(origin.getStorage()<transfer.getNum()){
            throw new ServiceException(CodeMsg.ORIGIN_NOT_ENOUGH);
        }
        origin.setStorage(transfer.getNum());
        target.setStorage(transfer.getNum());
        origin.setUpdateTime(new Date());
        target.setUpdateTime(new Date());
        storageDao.reduceStorage(origin);
        storageDao.increaseStorage(target);
    }

    public List<BookStorage> searchStorageByIsbn(String isbn){
        return storageDao.selectByIsbn(isbn);
    }

    public void deleteStorage(Integer id){
        storageDao.delete(id);
    }

}
